<?php
use App\Http\Controllers\Controller;
use Illuminate\Testing\Fluent\AssertableJson;
use App\Models\User;

uses(\Illuminate\Foundation\Testing\DatabaseTransactions::class);

test('auth', function (){
    $password='testing';
    $user=User::factory()->create([
        'password' => $password,
    ]);

    $response = $this->getJson('/api/user/info');
    $response->assertStatus(401);

    Log::debug("testing {$user->email} / {$password}");
    $response = $this->postJson('/api/login', ['email'=>$user->email, 'password'=>$password]);

    $response->assertStatus(200);
    $response->assertJson(fn (AssertableJson $json) =>
        $json->where('code', Controller::CODE_SUCCESS)
            ->has('data.token')
            ->etc()
    );

    $token=$response->json('data.token');
    Log::debug("token: $token");

    // validate user info
    $response = $this->withHeaders([
        'Authorization' => 'Bearer '.$token,
    ])->getJson('/api/user/info');
    $response->assertStatus(200);
    $response->assertJson(fn (AssertableJson $json) =>
        $json->where('code', Controller::CODE_SUCCESS)
            ->where('data.email', $user->email)
            ->etc()
    );
    Log::debug("user info: ".$response->json('data.email'));

    $response = $this->withHeaders([
        'Authorization' => 'Bearer '.$token,
    ])->postJson('/api/logout');

    $response->assertStatus(200);
    $response->assertJson(fn (AssertableJson $json) =>
        $json->where('code', Controller::CODE_SUCCESS)
            ->etc()
    );

});

